package com.fz.us.oa.web.controller;

import com.fz.us.admin.base.bean.Result;
import com.fz.us.admin.base.bean.jqgrid.JqGridFilter;
import com.fz.us.admin.base.bean.jqgrid.JqGridRule;
import com.fz.us.admin.base.bean.search.rule.Rule;
import com.fz.us.admin.base.bean.search.rule.RuleHelper;
import com.fz.us.admin.base.service.common.ResultService;
import com.fz.us.admin.base.utils.DataUtil;
import com.fz.us.admin.base.utils.LogUtil;
import com.fz.us.admin.base.utils.mapper.JsonMapper;
import com.fz.us.admin.company.entity.*;
import com.fz.us.admin.company.service.*;
import com.fz.us.admin.dict.dto.DictItemDto;
import com.fz.us.admin.dict.entity.Dict;
import com.fz.us.admin.dict.entity.DictItem;
import com.fz.us.admin.dict.service.DictItemService;
import com.fz.us.admin.dict.service.DictService;
import com.google.common.collect.Sets;
import net.sf.json.JSONObject;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.nio.charset.Charset;
import java.util.*;

/**
 * 控制器 - 基类
 * ============================================================================
 * 版权所有 2016 。
 *
 * @author fallenpanda
 * @version 1.0 2016-07-25 。
 * ============================================================================
 */
public class BaseController implements Serializable {

    @Autowired
    protected HttpServletRequest request;

    @Autowired
    protected ResultService resultService;

    @Autowired
    protected HttpServletResponse response;

    @Autowired
    private DictService dictService;
    @Autowired
    private DictItemService dictItemService;
    @Autowired
    private DutyService dutyService;
    @Autowired
    private UserService userService;
    @Autowired
    private ProcessBriefService processBriefService;
    @Autowired
    private StepBriefService stepBriefService;
    @Autowired
    private CommonConfigService commonConfigService;
    @Autowired
    private TaskEntityService taskEntityService;
    /**
     * 获取某一公司定义的字典项
     * @param user
     * @param value
     * @return
     */
    protected ArrayList<DictItem> getDictItems(User user, String value){
        ArrayList<DictItem> dictItems = new ArrayList<DictItem>();

        Company company = user.getCompany();
        Dict dict = dictService.getByValue(value);
        if (dict != null) {
            List<DictItemDto> dictItemDtoList = dictItemService.listSelectableDefined(dict.getId(), company.getId());
            for (DictItemDto entity : dictItemDtoList) {
                DictItem item = dictItemService.get(entity.id);
                dictItems.add(item);
            }
        }

        return dictItems;
    }

    protected HttpEntity ajax(Result result, MediaType mediaType) {
        return new ResponseEntity<String>(resultService.getBody(result), defaultHeaders(mediaType), result.getStatusCode());
    }

    protected HttpHeaders defaultHeaders(MediaType mediaType) {
        HttpHeaders headers = new HttpHeaders();
        headers.setCacheControl("no-store");
        headers.setContentType(new MediaType(mediaType.getType(), mediaType.getSubtype(), Charset.forName("utf-8")));
        headers.setDate(System.currentTimeMillis());
        headers.setPragma("no-cache");
        return headers;
    }

    protected HttpEntity ajaxJson(String message, HttpStatus statusCode) {
        return new ResponseEntity<String>(message, defaultHeaders(MediaType.APPLICATION_JSON), statusCode);
    }
    protected HttpEntity ajaxJson(Result result) {
        return new ResponseEntity<String>(resultService.getBody(result), defaultHeaders(MediaType.APPLICATION_JSON), result.getStatusCode());
    }

    protected HttpEntity ajaxJson(String str) {
        return new ResponseEntity<String>(str, defaultHeaders(MediaType.APPLICATION_JSON), HttpStatus.OK);
    }
    protected HttpEntity ajaxText(Result result) {
        return new ResponseEntity<String>(resultService.getBody(result), defaultHeaders(MediaType.TEXT_PLAIN), result.getStatusCode());
    }

    protected HttpEntity ajaxHtml(Result result) {
        return new ResponseEntity<String>(resultService.getBody(result), defaultHeaders(MediaType.TEXT_HTML), result.getStatusCode());
    }

    protected HttpEntity ajaxJson(Map map) {
        return new ResponseEntity<String>(JsonMapper.nonEmptyMapper().toJson(map), defaultHeaders(MediaType.APPLICATION_JSON), HttpStatus.OK);
    }

    // AJAX输出文本，返回null
    public String ajaxText(String text) {
        return ajax(text, "text/plain");
    }

    // AJAX输出HTML，返回null
    public String ajaxHtml(String html) {
        return ajax(html, "text/html");
    }

    // AJAX输出XML，返回null
    public String ajaxXml(String xml) {
        return ajax(xml, "text/xml");
    }

    // 根据字符串输出JSON，返回null
    public String ajaxStringJson(String jsonString) {
        return ajax(jsonString, "application/json");
    }

    // 根据Map输出JSON，返回null
    public String ajaxStringJson(Map<String, String> jsonMap) {
        JSONObject jsonObject = JSONObject.fromObject(jsonMap);
        return ajax(jsonObject.toString(), "application/json");
    }
    // AJAX输出，返回null
    public String ajax(String content, String type) {
        try {
            HttpServletResponse response = getResponse();
            response.setContentType(type + ";charset=UTF-8");
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            response.getWriter().write(content);
            response.getWriter().flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    // 获取Response
    public HttpServletResponse getResponse() {
        return this.response;
    }

    protected List<Rule> getSearchFilterRules(boolean _search, JqGridFilter filters){
        List<Rule> rules = new ArrayList<Rule>();
        if (_search && filters != null) {
            if (StringUtils.equals("AND", filters.getGroupOp())) {
                //查询条件
                if (filters.getRules() != null && filters.getRules().size() > 0) {
                    for (JqGridRule rule : filters.getRules()) {
                        if (StringUtils.isNotEmpty(rule.getField()) && StringUtils.isNotEmpty(rule.getOp()) && StringUtils.isNotEmpty(rule.getData())) {
                            String field = rule.getField();
                            if (StringUtils.contains(field, "_")){
                                field = StringUtils.replace(field, "_", ".");
                            }

                            String op = rule.getOp();
                            Object data = rule.getData();


                            if (StringUtils.equals(op, "eq"))
                                rules.add(RuleHelper.eq(field, data));
                            else if (StringUtils.equals(op, "ne"))
                                rules.add(RuleHelper.ne(field, data));
                            else if (StringUtils.equals(op, "lt"))
                                rules.add(RuleHelper.lt(field, data));
                            else if (StringUtils.equals(op, "le"))
                                rules.add(RuleHelper.le(field, data));
                            else if (StringUtils.equals(op, "gt"))
                                rules.add(RuleHelper.gt(field, data));
                            else if (StringUtils.equals(op, "ge"))
                                rules.add(RuleHelper.ge(field, data));
//                                else if (StringUtils.equals(op, "bw"))// begins with
//                                    rules.add(RuleHelper.bw(field, data));
//                                else if (StringUtils.equals(op, "bn"))// does not begin with
//                                    rules.add(RuleHelper.bn(field, data));
//                                else if (StringUtils.equals(op, "ew"))// ends with
//                                    rules.add(RuleHelper.ew(field, data));
//                                else if (StringUtils.equals(op, "en"))// does not end with
//                                    rules.add(RuleHelper.en(field, data));
                            else if (StringUtils.equals(op, "cn")){
                                if(field.equals("createTime")){
                                    rules.add(RuleHelper.like(field, DataUtil.StringToDate(data.toString())));
                                }else{
                                    rules.add(RuleHelper.like(field,  data));
                                }
                            }

//                                else if (StringUtils.equals(op, "nc"))// does not contain
//                                    rules.add(RuleHelper.nc(field, data));
                            else if (StringUtils.equals(op, "nu"))
                                rules.add(RuleHelper.isNull(field));
                            else if (StringUtils.equals(op, "nn"))
                                rules.add(RuleHelper.isNotNull(field));
                            else if (StringUtils.equals(op, "in"))
                                rules.add(RuleHelper.in(field, StringUtils.split(data.toString(), ",")));
//                                else if (StringUtils.equals(op, "ni"))// is not in
//                                    rules.add(RuleHelper.ni(field, data));
                        }
                    }
                }
            }
        }

        return rules;
    }

    public ResponseEntity<byte[]> fileDownload(InputStream in, String fileName) throws IOException {
        return fileDownload(in, fileName, MediaType.APPLICATION_OCTET_STREAM);
    }

    public ResponseEntity<byte[]> fileDownload(InputStream in, String fileName, MediaType mediaType) throws IOException {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(mediaType);
        headers.setContentDispositionFormData("attachment", new String(fileName.getBytes(), "ISO8859-1"));
        return new ResponseEntity<byte[]>(IOUtils.toByteArray(in), headers, HttpStatus.CREATED);
    }

    /**
     * 创建按钮权限判断
     * @param businessKey
     * @return
     */
    public String isCreate(String businessKey){
        User loginer = userService.getLoginInfo();
        if(StringUtils.isEmpty(businessKey)){
            return "style='display:none'";
        }
        ProcessBrief processBrief = processBriefService.getInfoByTableKey(businessKey);
        if(processBrief == null){
            return "style='display:none'";
        }

        StepBrief stepBrief = stepBriefService.getInfoByStepNo(processBrief, 1);
        if(stepBrief == null){
            return "style='display:none'";
        }
        List<Duty> dutyList = commonConfigService.findDutyByConfig(stepBrief.getCommonConfig().getId());
        dutyList.retainAll(dutyService.getDutys(loginer));
        if(dutyList.size() > 0){
            return "";
        }
        return "style='display:none'";

    }

    /**
     * 编辑权限
     * @param keyId
     * @return
     */
    public String isEdit(String keyId){
        User user = userService.getLoginInfo();
        TaskEntity taskEntity = taskEntityService.getInfoByKeyId(keyId);
        //归档后编辑者权限
        if(StringUtils.equals(taskEntity.getProcessState().name(),"Finished")){
            ProcessBrief processBrief = processBriefService.getInfoByTableKey(taskEntity.getEntityName());
            Set<Duty> editDutySet = Sets.newHashSet();
            if(processBrief.getEditConfig() != null){
                editDutySet.addAll(commonConfigService.findDutyByConfig(keyId, taskEntity.getEntityName(), processBrief.getEditConfig().getId()));
            }
            for(Duty duty:editDutySet){
                if(duty.getUser() == user){
                    return "";
                }
            }
        }else{//流转，第一步，只有新建人有权限
            if(taskEntity.getStepNo() == 1){
                if(taskEntity.getCreater() == user){
                    return "";
                }
            }
        }
        return  "style='display:none'";
    }
}
